package biz.core.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import biz.core.domain.UserInfo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import exception.BaseException;
import exception.PermissionsException;

/**
 * @author JohnCheng
 * @CreateDate 2009-3-13
 */
public abstract class BaseAction<T> extends ActionSupport {

	public final static boolean DEBUG = true;

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private static final long serialVersionUID = -5383214833628030398L;

	private String retURL = "";

	private String id;

	private String txtResult;

	/*
	 * 获取当前登陆用户信息
	 */
	protected UserInfo getCurrentUser() throws Exception {
		UserInfo ui = (UserInfo) ActionContext.getContext().getSession().get(UserInfo.USER_SESSION_KEY);
		if (ui == null && DEBUG) {
			ui = new UserInfo();
			ui.setLoginName("admin");
			ui.setUserId("20090101010000000001");
			return ui;
		}
		if (ui == null) {
			if (logger.isDebugEnabled())
				logger.debug("Not Login.");
			throw new PermissionsException(BaseException.NOT_LOGIN_ERROR_CODE);
		}
		return ui;
	}

	/*
	 * 当前登陆用户的用户ID
	 */
	protected Integer getUserId() throws Exception {
		return Integer.valueOf(getCurrentUser().getUserId());
	}

	/*
	 * 从Spring容器中获取Bean实例
	 */
	public Object getBean(String name) {
		Object o = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext()).getBean(name);
		return o;
	}

	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	public HttpSession getSession() {
		return ServletActionContext.getRequest().getSession();
	}

	public String getTxtResult() {
		return txtResult;
	}

	public void setTxtResult(String txtResult) {
		this.txtResult = txtResult;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}


	public String getRetURL() {
		if (StringUtils.isEmpty(this.retURL))
			retURL = getRequest().getHeader("Referer");
		return retURL;
	}

	public void setRetURL(String retURL) {
		this.retURL = retURL;
	}

}
